<template>
  <div class="app-container">
    <a-space direction="vertical" :style="{ width: '100%' }" :size="[0, 48]">
      <div class="content">
        <div class="left">
          <p class="text p-16px">产品信息</p>
          <Anchor />
        </div>
        <div class="right">
          <div class="py-20px px-30px mt-20px">
            <p class="title">基础信息</p>
            <div class="base">
              <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="120px"
                :disabled="view == 1"
              >
                <el-form-item label="产品名称" prop="productName">
                  <el-input
                    v-model="form.productName"
                    placeholder="请输入产品名称"
                  />
                </el-form-item>
                <el-form-item label="产品类别" prop="dictValue">
                  <!-- 级联选择器 -->
                  <el-cascader
                    style="width: 100%"
                    v-model="form.dictValue"
                    @change="changeDictValue"
                    :options="treeOptions"
                    :props="{
                      emitPath: false,
                      checkStrictly: true,
                      label: 'dictName',
                      value: 'dictValue',
                      children: 'children',
                    }"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="产品特性标签">
                  <el-select
                    style="width: 100%"
                    v-model="form.modelLabels"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="输入需要的关键词 回车键添加"
                    @remove-tag="handleRemoveTag"
                  >
                  </el-select>
                </el-form-item>
                <el-form-item label="产品描述" prop="productNotes">
                  <el-input
                    v-model="form.productNotes"
                    placeholder="请输入产品描述"
                    type="textarea"
                    maxlength="9999"
                    show-word-limit
                  />
                </el-form-item>

                <el-form-item label="领域分类">
                  <el-cascader
                    v-model="form.fieldIds"
                    :options="domainList"
                    :props="{
                      multiple: true,
                      emitPath: false,
                      label: 'areaTitle',
                      value: 'id',
                      children: 'children',
                    }"
                    collapse-tags
                    clearable
                  />
                </el-form-item>
                <el-form-item label="专题分类">
                  <el-cascader
                    v-model="form.topicIds"
                    :options="special"
                    :props="{
                      multiple: true,
                      emitPath: false,
                      label: 'areaTitle',
                      value: 'id',
                      children: 'children',
                    }"
                    collapse-tags
                    clearable
                  />
                </el-form-item>
                <el-form-item label="展示范围">
                  <el-cascader
                    v-model="form.dataScope"
                    :options="scopeList"
                    :props="{
                      multiple: false,
                      emitPath: false,
                      label: 'label',
                      value: 'value',
                      children: 'children',
                    }"
                    collapse-tags
                    clearable
                  />
                </el-form-item>

                <el-form-item label="分类编码">
                  <template v-for="(item, index) in form.classifyList">
                    <div class="classCode" v-if="index == 0">
                      <div class="oneCode">{{ item.label }}</div>
                      <div style="margin-left: 10px; width: 100%">
                        <el-input v-model="item.value" disabled></el-input>
                      </div>
                    </div>
                    <div class="classifyList group" v-else>
                      <div class="item">
                        <el-input
                          v-model="item.label"
                          type="text"
                          placeholder="输入编码名称"
                        />
                        <el-input
                          v-model="item.value"
                          type="text"
                          placeholder="输入其他编码标准"
                        />
                        <el-icon v-if="!view" @click="removeCode(item)"
                          ><RemoveFilled
                        /></el-icon>
                      </div>
                    </div>
                  </template>
                  <div class="addClassBtn">
                    <el-button plain :icon="Plus" @click="addCode"
                      >新增编码</el-button
                    >
                  </div>
                </el-form-item>
                <el-form-item label="模型上传">
                  <div
                    class="model"
                    v-for="(item, index) in form.modelFiles"
                    :key="index"
                  >
                    <div class="upload">
                      <FragmentUpload
                        ref="uploadModelRef"
                        :limit="1"
                        btn-name="模型上传"
                        @file-uploaded="FileUploadedModel($event, index)"
                        @file-remove="handleRemoveFileModel($event, index)"
                        :Filelist="
                          item.fileName
                            ? [{ id: item.id, name: item.fileName, url }]
                            : []
                        "
                        :maxSize="500"
                        accept="*"
                        :fileType="'*'"
                        label="00"
                      />
                    </div>
                    <div class="tips">
                      <el-tooltip
                        popper-class="box-item"
                        effect="dark"
                        placement="top-start"
                      >
                        <template #content>
                          <div style="width: 200px">
                            ①　Revit支持类型adsk. pcg、 rfa. rvt. slog. rft
                            ;②　ArchiCAD支持类型pmk、 pla. prf、 mod. tpl. aat.
                            spr, rpr. lbk. lcy、 2dl. lay.pln
                            :③　PKPM-PC支持类型pce、 pc. pcx、 pbims2
                            ;④　FBX支持类型fbx⑤　其它模型支持类型p3d ;
                          </div>
                        </template>
                        <div class="tip">
                          <el-icon><QuestionFilled /></el-icon
                          ><span> 支持的文件格式 </span>
                        </div>
                      </el-tooltip>
                    </div>
                    <div class="selectType">
                      <el-cascader
                        style="width: 100%"
                        v-model="item.fileFormat"
                        :options="modelTypeList"
                        :props="{
                          emitPath: false,
                          label: 'label',
                          value: 'id',
                          children: 'children',
                        }"
                        clearable
                      />
                    </div>
                    <div class="selectVersion">
                      <el-select
                        v-model="item.yearVersion"
                        placeholder="请选择或自定义输入"
                      >
                        <el-option
                          v-for="(item1, index) in versionList"
                          :key="item1.id"
                          :label="item1.label"
                          :value="item1.label"
                        />
                        <template #footer>
                          <el-input
                            v-model="opthonsName"
                            class="option-input"
                            placeholder="输入自定义版本"
                            size="small"
                          />
                          <el-button
                            type="primary"
                            size="small"
                            @click="onConfirm(index)"
                          >
                            添加
                          </el-button>
                          <!-- <el-button size="small" @click="clear"
                            >取消</el-button
                          > -->
                        </template>
                      </el-select>
                    </div>
                    <div class="modelFineness">
                      <el-cascader
                        placeholder="选择模型细度"
                        v-model="item.modelFineness"
                        :options="finenessList"
                        :props="{
                          multiple: false,
                          emitPath: false,
                          label: 'label',
                          value: 'value',
                          children: 'children',
                        }"
                        collapse-tags
                        clearable
                      />
                    </div>

                    <div class="remove" v-if="!view">
                      <el-icon @click="removeModel(item)">
                        <RemoveFilled
                      /></el-icon>
                    </div>
                  </div>
                  <div class="addClassBtn">
                    <el-button plain :icon="Plus" @click="addModel"
                      >新增模型</el-button
                    >
                  </div>
                </el-form-item>
                <el-form-item label="预览图片">
                  <NewImgUpload
                    tip="图片格式为jpg\png\gif，并校验图片像素不少于320*320,大小不超过2M,最多5张图片"
                    :limit="5"
                    @file-uploaded="handleImgUploaded"
                    :Filelist="form.previewFiles"
                    @file-remove="handleImgRemove"
                    label="00"
                  />
                </el-form-item>
              </el-form>
            </div>
            <p class="title">产品属性</p>
            <div class="attribute">
              <ProductAttr
                :view="view"
                ref="productAttrRef"
                :list="form.attributeList"
                @removeGroup="removeGroup"
                @removeItem="removeItem"
              />
            </div>
            <p class="title">文档</p>
            <div class="uploadDoc">
              <el-form :disabled="view == 1">
                <el-form-item label="上传文档">
                  <FragmentUpload
                    :limit="1"
                    tip="注：文件大小不超过50M。"
                    btn-name="上传文档"
                    @file-uploaded="FileUploadDoc"
                    @file-remove="handleRemoveFileDoc"
                    :Filelist="form.textFiles"
                    :maxSize="500"
                    accept="*"
                    :fileType="'*'"
                    label="00"
                  />
                </el-form-item>
              </el-form>
            </div>
            <p class="title">图纸</p>
            <div class="uploadDoc">
              <el-form :disabled="view">
                <el-form-item label="上传图纸">
                  <FragmentUpload
                    :limit="1"
                    tip="注：文件大小不超过50M。"
                    btn-name="上传图纸"
                    @file-uploaded="FileUploadDrawing"
                    @file-remove="handleRemoveFileDrawing"
                    :Filelist="form.drawFiles"
                    :maxSize="500"
                    accept="*"
                    :fileType="'*'"
                    label="00"
                  />
                </el-form-item>
              </el-form>
            </div>

            <p class="title">案例</p>
            <div class="case">
              <el-form
                :model="form"
                :rules="rules"
                label-width="120px"
                :disabled="view"
              >
                <el-form-item label="案例名称" prop="username">
                  <el-input v-model="form.caseName" placeholder="" />
                </el-form-item>
                <el-form-item label="案例图片" prop="username">
                  <NewImgUpload
                    tip="图片格式为jpg\png\gif，并校验图片像素不少于320*320,大小不超过2M,最多5张图片"
                    :limit="5"
                    @file-uploaded="handlecaseImgUploaded"
                    :Filelist="form.caseFiles"
                    @file-remove="handleanliImgRemove"
                    label="00"
                  />
                </el-form-item>
                <el-form-item label="模型类型" prop="username">
                  <div class="selectType" style="width: 100%">
                    <el-cascader
                      style="width: 100%"
                      v-model="form.fileFormat"
                      @change="handleModelTypeChange"
                      :options="modelTypeList"
                      :props="{
                        emitPath: false,
                        label: 'label',
                        value: 'id',
                        children: 'children',
                      }"
                      clearable
                    />
                  </div>
                  <div class="upload">
                    <el-row style="width: 400px">
                      <el-col :span="12">
                        <FragmentUpload
                          :limit="1"
                          tip="注：文件大小不超过50M1。"
                          btn-name="上传文件"
                          @file-uploaded="FileUploadedCase"
                          @file-remove="handleRemoveFileCase"
                          :Filelist="form.caseModelFiles"
                          :maxSize="500"
                          accept="*"
                          :fileType="'*'"
                          label="00"
                        />
                      </el-col>
                      <el-col
                        :span="12"
                        style="display: flex; align-items: center"
                      >
                        <el-tooltip
                          popper-class="box-item"
                          effect="dark"
                          placement="top-start"
                          style="margin-top: 30px"
                        >
                          <template #content>
                            <div style="width: 200px">
                              ①　Revit支持类型adsk. pcg、 rfa. rvt. slog. rft
                              ;②　ArchiCAD支持类型pmk、 pla. prf、 mod. tpl.
                              aat. spr, rpr. lbk. lcy、 2dl. lay.pln
                              :③　PKPM-PC支持类型pce、 pc. pcx、 pbims2
                              ;④　FBX支持类型fbx⑤　其它模型支持类型p3d ;
                            </div>
                          </template>
                          <div class="tip">
                            <el-icon><QuestionFilled /></el-icon
                            ><span> 支持的文件格式 </span>
                          </div>
                        </el-tooltip>
                      </el-col>
                    </el-row>
                  </div>
                </el-form-item>
              </el-form>
            </div>

            <p class="title">制作者信息</p>
            <div class="userInfo">
              <el-form
                :model="form"
                :rules="rules"
                label-width="120px"
                :disabled="view"
              >
                <el-form-item label="制作者" prop="username">
                  <el-input v-model="form.producer" placeholder="" disabled />
                </el-form-item>
                <el-form-item label="产品二维码" prop="username">
                  <NewImgUpload
                    tip="图片格式为jpg\png\gif，并校验图片像素不少于320*320,大小不超过2M,最多5张图片"
                    :limit="5"
                    @file-uploaded="handleQrCodeImgUploaded"
                    @file-remove="handleQrImgRemove"
                    :Filelist="form.qrFiles"
                    label="00"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </a-space>
    <!-- 上传选择 -->

    <!-- 底部 -->
    <div class="footer" v-if="!view">
      <a-space>
        <a-button @click="onCancel"> 取消 </a-button>
        <a-button type="primary" @click="onSubmit(0)"> 保存为草稿 </a-button>
        <a-button type="primary" @click="onSubmit(1)"> 提交审批 </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup>
import { Plus, Upload } from "@element-plus/icons-vue";
import NewImgUpload from "@/components/newImgUpload/newImgUpload";

import FragmentUpload from "@/components/FragmentUpLoad/index.vue"; //分片上传组件
import { rules } from "./rules";
import Anchor from "./cpns/anchor.vue";
import ProductAttr from "./cpns/productAttr.vue";
import { useRouter, useRoute } from "vue-router";
import {
  getDickAllTreeListRequest,
  getModelTypeListRequest,
  getCodeRequest,
  saveModelRequest,
  getModelDetailById,
} from "@/api/buildlibrary";
import { getTypeListRequest } from "@/api/public";
import { getDomainListRequest } from "@/api/buildlibrary/domain.js";
import { nextTick, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();

const { id, view } = route.query;

onMounted(() => {
  getTreeList();
  getModelTypeList();
  getModelversion();

  getdomain();
  getspecial();
  getscope();
  getfineness();

  console.log(route);
  if (id) {
    console.log("编辑模式", id);
    getEditInfo(id);
  } else {
    console.log("新增模式");
  }
});

//编辑模式数据回显方法
const getEditInfo = async (id) => {
  const { data: res } = await getModelDetailById(id);

  console.log(res);
  form.id = res.id;
  form.classifyId = res.classifyId;
  form.productName = res.productName;
  form.dictValue = res.dictValue;
  form.TempModelLabels = res.modelLabels;
  form.modelLabels = res.modelLabels?.map((item) => {
    return item.label;
  });
  form.productNotes = res.productNotes;
  form.fieldIds = res.fieldIds;
  form.topicIds = res.topicIds;

  form.dataScope = res.dataScope?.toString(); //展示范围

  form.classifyList = res.classifyList;
  form.modelFiles = res.modelFiles;
  form.previewFiles = res.previewFiles?res.previewFiles.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
      url: item.filePath,
      ...item,
    };
  }):[]
  form.attributeList = res.attributeList;
  form.textFiles = res.textFiles?.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
      url: item.filePath,
      ...item,
    };
  });
  form.drawFiles = res.drawFiles?.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
      url: item.filePath,
      ...item,
    };
  });
  form.caseName = res.caseName;
  form.caseFiles = res.caseFiles
    ? res.caseFiles.map((item) => {
        return {
          name: item.fileName,
          id: item.id,
          url: item.filePath,
          ...item,
        };
      })
    : [];

  form.fileFormat = res.caseModelFiles ? res.caseModelFiles[0]?.fileFormat : "";
  handleModelTypeChange(form.fileFormat);

  form.caseModelFiles = res.caseModelFiles?.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
      url: item.filePath,
      ...item,
    };
  });
  form.producer = res.producer;
  form.qrFiles = res.qrFiles
    ? res.qrFiles.map((item) => {
        return {
          name: item.fileName,
          id: item.id,
          url: item.filePath,
          ...item,
        };
      })
    : [];
};

const form = reactive({
  resourceType: 1, //来源 后台
  productName: "", //产品名称
  dictValue: "", //产品类别
  modelLabels: [], //产品标签
  productNotes: "", //产品描述
  fieldIds: [], //领域id
  topicIds: [], //专题分类
  dataScope: "0", // 展示范围 权限范围：0 公开 1个人 2内部
  modelFineness: "", //模型细度
  classifyList: [
    {
      label: "GB51269-2017",
      value: "",
    },
  ],
  //模型数组
  modelFiles: [
    {
      fileId: "",
      fileName: "",
      fileSize: "",
      fileFormat: "",
      yearVersion: "",
      modelFineness: "",
    },
    {
      fileId: "",
      fileName: "",
      fileSize: "",
      fileFormat: "",
      yearVersion: "",
      modelFineness: "",
    },
    {
      fileId: "",
      fileName: "",
      fileSize: "",
      fileFormat: "",
      yearVersion: "",
      modelFineness: "",
    },
  ],
  //预览图数组
  previewFiles: [],
  attributeList: [], //产品属性 自定义规则组

  textFiles: [], //文档文件集合
  drawFiles: [], //图纸文件集合

  caseName: "", //案例名称
  caseFiles: [], //案例文图片件集合
  caseModelFiles: [], //案例中的模型文件

  producer: "", //制作者
  qrFiles: [], //二维码文件

  delCustomsIds: [], //删除的分类数据
  delFileIds: [], //删除文件id合集
});
const productAttrRef = ref(null);

//添加分类
const addCode = () => {
  form.classifyList.push({
    label: "",
    value: "",
  });
};

let deltag = ref([]);
//移除tag
const handleRemoveTag = (tagValue) => {
  form.TempModelLabels.forEach((item) => {
    if (tagValue == item.label) {
      deltag.value.push(item.label);
      // item.delFlag = 1;
    }
  });
};

//移除分类
const removeCode = (item) => {
  console.log(item);
  form.delCustomsIds.push(item.id);
  form.classifyList.splice(form.classifyList.indexOf(item), 1);
};
//添加模型
const addModel = () => {
  if (!form.modelFiles) {
    form.modelFiles = [];
  }
  form.modelFiles.push({
    fileId: "",
    fileName: "",
    fileSize: "",

    fileFormat: "",
    yearVersion: "",
    modelFineness: "",
  });
};
//移除模型
const removeModel = (item) => {
  console.log(item);
  form.delFileIds.push(item.id);
  form.modelFiles.splice(form.modelFiles.indexOf(item), 1);
};

//获取多级分类
const treeOptions = ref([]);
const getTreeList = async () => {
  const res = await getDickAllTreeListRequest({ dictType: 1, level: 5 });
  treeOptions.value = res.data;
  console.log(res);
};

//获取模型分类
const modelTypeList = ref([]);
const getModelTypeList = async () => {
  const res = await getModelTypeListRequest({ model: { type: 0 }, size: 999 });
  console.log(res);
  modelTypeList.value = res.data.records;
  // console.log(modelType.data);
};

//获取版本信息
const versionList = ref([]);
const getModelversion = async () => {
  const res = await getModelTypeListRequest({ model: { type: 1 } });
  console.log(res);
  versionList.value = res.data.records;
  // console.log(modelType.data);
};

let domainList = ref([]); //领域分类
//获取领域分类
const getdomain = async () => {
  const res = await getDomainListRequest({
    current: 1,
    size: 999,
    model: {
      type: 42,
      shelfStatus: 1,
    },
  });
  console.log(res);
  res.data.records.forEach((item) => {
    if (!item.children.length > 0) {
      item.disabled = true;
    }
  });
  domainList.value = res.data.records;
};

let special = ref([]); //特殊分类
const getspecial = async () => {
  const res = await getDomainListRequest({
    current: 1,
    size: 999,
    model: {
      type: 43,
      shelfStatus: 1,
    },
  });
  console.log(res);
  special.value = res.data.records;
};

let scopeList = ref([]); //展示范围
const getscope = async () => {
  const res = await getTypeListRequest({
    // current: 1,

    model: {
      type: 13,
    },
    size: 999,
  });
  console.log(res);
  scopeList.value = res.data.records;
};

let finenessList = ref([]); //模型细度
const getfineness = async () => {
  const res = await getTypeListRequest({
    // current: 1,

    model: {
      type: 14,
    },
    size: 999,
  });
  console.log(res);
  res.data.records.forEach((item) => {
    item.value = parseInt(item.value);
  });
  finenessList.value = res.data.records;
};

//模型移除事件
const handleRemoveFileModel = (data, i) => {
  console.log(data);
  form.delFileIds.push(data.id);
  form.modelFiles[i] = {
    fileId: "",
    fileName: "",
    fileSize: "",

    fileFormat: "",
    yearVersion: "",
    modelFineness: "",
  };
};

//模型上传事件处理
const FileUploadedModel = (data, i) => {
  console.log(data, i);
  let str = data.name;
  let index = str.lastIndexOf("\.");
  str = str.substring(index + 1, str.length);
  let back = handleModelTypeChange1(str);
  if (back) {
    form.modelFiles[i].fileFormat = back;
  } else {
    ElMessage.error("请上传正确的的格式");
    form.modelFiles.splice(i, 1);
    nextTick(() => {
      form.modelFiles.splice(i, 0, {
        fileId: "",
        fileName: "",
        fileSize: "",

        fileFormat: "",
        yearVersion: "",
        modelFineness: "",
      });
    });
    return false;
  }
  form.modelFiles[i].fileId = data.id;
  form.modelFiles[i].fileName = data.name;
  form.modelFiles[i].fileSize = data.size;
};

//添加选项
const opthonsName = ref("");
const onConfirm = (index) => {
  versionList.value.push({
    label: opthonsName.value,
  });
  opthonsName.value = "";
};

//缩略图上传处理事件
const handleImgUploaded = (data) => {
  if (!form.previewFiles) {
    form.previewFiles = [];
  }
  form.previewFiles.push({
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
    name: data.name,
    id: data.id,
    url: data.path,
  });
  console.log(data);
};
//缩略图删除处理
const handleImgRemove = (data) => {
  console.log(data);
  let fileId = "";
  if (data.fileId) {
    fileId = data.id;
  } else {
    fileId = data.response.data[0].id;
  }

  form.delFileIds.push(fileId);

  form.previewFiles.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.previewFiles.splice(item, 1);
    }
  });
};

//案例图片上传处理
const handlecaseImgUploaded = (data) => {
  console.log(data);
  if (!form.caseFiles) {
    form.caseFiles = [];
  }
  form.caseFiles.push({
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
    name: data.name,
    id: data.id,
    url: data.path,
  });
};
//案例图片删除
const handleanliImgRemove = (data) => {
  console.log(data);
  let fileId = "";
  if (data.fileId) {
    fileId = data.id;
  } else {
    fileId = data.response.data[0].id;
  }

  form.delFileIds.push(fileId);

  form.caseFiles.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.caseFiles.splice(item, 1);
    }
  });
};

//二维码上传处理事件
const handleQrCodeImgUploaded = (data) => {
  if (!form.qrFiles) {
    form.qrFiles = [];
  }
  form.qrFiles.push({
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
    name: data.name,
    id: data.id,
    url: data.path,
  });
  console.log(data);
};
//二维码图片移除事件
const handleQrImgRemove = (data) => {
  console.log(data);
  let fileId = "";
  if (data.fileId) {
    fileId = data.id;
  } else {
    fileId = data.response.data[0].id;
  }

  form.delFileIds.push(fileId);

  form.qrFiles.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.qrFiles.splice(item, 1);
    }
  });
};

//文档上传 事件处理
const FileUploadDoc = (data) => {
  console.log(data);
  if (!form.textFiles) {
    form.textFiles = [];
  }
  form.textFiles.push({
    name: data.name,
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
  });
};
//文档移除 事件处理
const handleRemoveFileDoc = (data) => {
  console.log(data);
  let fileId = "";
  if (data.id) {
    fileId = data.id;
  } else {
    fileId = data.response.id;
  }
  form.delFileIds.push(fileId);

  form.textFiles.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.textFiles.splice(item, 1);
    }
  });
};
// 图纸上传 事件处理
const FileUploadDrawing = (data) => {
  console.log(data);
  if (!form.drawFiles) {
    form.drawFiles = [];
  }
  form.drawFiles.push({
    name: data.name,
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
  });
};
//图纸移除 事件处理
const handleRemoveFileDrawing = (data) => {
  console.log(data);
  let fileId = "";
  if (data.id) {
    fileId = data.id;
  } else {
    fileId = data.response.id;
  }
  form.delFileIds.push(fileId);

  form.drawFiles.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.drawFiles.splice(item, 1);
    }
  });
};
//案例模型 上传 事件处理
const FileUploadedCase = (data) => {
  console.log(data);
  if (!form.caseModelFiles) {
    form.caseModelFiles = [];
  }
  form.caseModelFiles.push({
    name: data.name,
    fileId: data.id,
    fileName: data.name,
    fileSize: data.size,
  });
};
//案例模型 移除 事件处理
const handleRemoveFileCase = (data) => {
  console.log(data);
  let fileId = "";
  if (data.id) {
    fileId = data.id;
  } else {
    fileId = data.response.id;
  }
  form.delFileIds.push(fileId);

  form.caseModelFiles.forEach((item) => {
    console.log(item);
    if (item.fileId === fileId) {
      form.caseModelFiles.splice(item, 1);
    }
  });
};

//根据选择获取编码
const changeDictValue = async (value) => {
  console.log(value);
  const res = await getCodeRequest({ salt: value });
  form.classifyList[0].value = res.data;

  // let classifyId = "";
  //递归查找 treeOptions.value 里的dictValue
  function deep(value, list) {
    list.forEach((item) => {
      if (item.dictValue === value) {
        form.classifyId = item.id;
      }
      if (item.children) {
        deep(value, item.children);
      }
    });
  }
  deep(value, treeOptions.value);

  const parentIdList = findParentIds(treeOptions.value, form.classifyId);
  form.classifyId = parentIdList;
  console.log(parentIdList); // 输出630,6298,5939
};

function findParentIds(data, searchId) {
  let result = [];
  //name——某字段，value——值
  function findParents(treeData, id) {
    if (treeData.length == 0) return;
    for (let i = 0; i < treeData.length; i++) {
      if (treeData[i].id == id) {
        return [id];
      } else {
        if (treeData[i].children) {
          let res = findParents(treeData[i].children, id);
          if (res !== undefined) {
            return res.concat(treeData[i].id);
          }
        }
      }
    }
  }
  let arr = findParents(data, searchId);
  // return [...arr, searchId];

  return arr.reverse().join(",");
  // console.log(arr);
}

//取消
const onCancel = () => {
  router.go(-1);
};
const formRef = ref(null);
//提交表单
const onSubmit = async (productState) => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage({
        message: "请填写完整信息。",
        type: "warning",
      });
      return false;
    }
    form.productState = productState;
    //新增逻辑
    if (!id) {
      form.modelLabels = form.modelLabels?.map((item) => {
        return {
          label: item,
          classifyType: 0,
        };
      });

      let newForm = {};
      for (const key in form) {
        //有值的 才添加进 newForm

        if (form[key] || form[key] === 0) {
          if (form[key] instanceof Array) {
            if (form[key].length > 0) {
              if (key === "modelFiles") {
                newForm[key] = form[key].filter((item) => {
                  return item.fileId;
                });
                if (newForm[key].length === 0) {
                  delete newForm[key];
                }
              } else {
                newForm[key] = form[key];
              }
            }
          } else {
            newForm[key] = form[key];
          }
        }
      }
      newForm.producer = window.localStorage.getItem("userid");

      // 产品参数
      const attributeList = await productAttrRef.value.verificationOk();
      newForm.attributeList = attributeList;
      console.log(attributeList);

      //把modelLabels的数据 从[{label:1},{label:2}] 重置成 [1,2}]
      if (form.modelLabels.length > 0) {
        form.modelLabels = form.modelLabels.map((item) => {
          return item.label;
        });
      }

      const res = await saveModelRequest(newForm);
      if (res.data) {
        ElMessage.success("提交成功");
        router.go(-1);
      }

      console.log(res);
    } else {
      //编辑逻辑
      let newForm = {};
      newForm = JSON.parse(JSON.stringify(form));
      delete newForm.fileFormat;
      delete newForm.producer;
      newForm.modelFiles = newForm.modelFiles?.filter((item) => {
        return item.fileId;
      });

      newForm.modelLabels = form.modelLabels.map((item) => {
        let temp = {};
        for (const item1 of form.TempModelLabels) {
          if (item1.label === item) {
            temp = item1;
            break;
          } else {
            temp = {
              label: item,
              classifyType: 0,
            };
          }
        }
        return temp;
      });
      deltag.value.forEach((item) => {
        for (const item1 of form.TempModelLabels) {
          if (item === item1.label) {
            item1.delFlag = 1;
            newForm.modelLabels.push(item1);
          }
        }
      });

      delete newForm.TempModelLabels;

      const res = await saveModelRequest(newForm);
      if (res.data) {
        ElMessage.success("保存成功");
        router.go(-1);
      }

      console.log(res);
    }
  });

  console.log(form);
};

const removeGroup = (data) => {
  form.delCustomsIds.push(data);
};
const removeItem = (data) => {
  form.delCustomsIds.push(data);
};

let upflag = ref(true);
const handleModelTypeChange = (value) => {
  form.caseModelFiles = [];

  //在 modelTypeList 里面递归查找 value 返回其label
  for (let i = 0; i < modelTypeList.value.length; i++) {
    //每一项还有children
    if (modelTypeList.value[i].children) {
      for (let j = 0; j < modelTypeList.value[i].children.length; j++) {
        if (modelTypeList.value[i].children[j].id === value) {
          accept.value = modelTypeList.value[i].children[j].label;
          break;
        }
      }
    }
  }
  if (value === null) {
    accept.value = "";
  }
  console.log(value);
};

//根据label值 返回其id
const handleModelTypeChange1 = (label) => {
  //在 modelTypeList 里面递归查找 value 返回其label
  for (let i = 0; i < modelTypeList.value.length; i++) {
    //每一项还有children
    if (modelTypeList.value[i].children) {
      for (let j = 0; j < modelTypeList.value[i].children.length; j++) {
        if (modelTypeList.value[i].children[j].label === label) {
          console.log(111111);
          return modelTypeList.value[i].children[j].id;
        }
      }
    }
  }
};

let accept = ref("");

//从cookie获取制作者信息
form.producer = window.localStorage.getItem("username");
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  justify-content: space-between;
  .left {
    min-width: 200px;
    p {
      font-size: 16px;
      text-align: center;
    }
  }
  .right {
    flex: 1;
    margin-left: 30px;
    margin-bottom: 100px;
    .title {
      font-size: 16px;
      color: #333;
      font-weight: 700;
      position: relative;
      &::before {
        position: absolute;
        left: -10px;
        content: "";
        display: block;
        width: 4px;
        height: 20px;
        background-color: #00a0e9;
      }
    }
  }
}
// 基础信息
.base {
  padding: 10px 200px 0 100px;
  .classCode {
    display: flex;
    width: 100%;
    .oneCode {
      width: 110px;
    }
  }
  .group {
    width: 100%;
    .item {
      display: flex;
      align-items: center;
      margin: 20px 0;
      .el-input {
        margin-right: 10px;
      }
      .el-icon {
        font-size: 22px;
        color: #ccc;
        cursor: pointer;
      }
    }
  }
  .addClassBtn {
    margin-top: 20px;
  }

  .model {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 10px;
    .tips {
      .tip {
        display: flex;
        align-items: center;
        color: rgb(0, 160, 233);
        width: 130px;
        span {
          margin-left: 10px;
        }
      }
    }
    .selectType {
      width: 240px;
      .el-select {
        width: 100%;
      }
    }
    .selectVersion {
      width: 130px;
      .el-select {
        width: 100%;
      }
    }
    .remove {
      font-size: 22px;
      color: #ccc;
      cursor: pointer;
    }
  }
}
//产品属性
.attribute {
  .add {
    width: 100%;
  }
}
//案例
.case {
  padding: 10px 200px 0 100px;
  .upload {
    // width: 100%;
    color: #00a0e9;
    margin-top: 10px;
    // display: flex;
    //align-items: center;
    //justify-content: left;
  }
}
.userInfo {
  padding: 10px 200px 0 100px;
}

.footer {
  width: 100%;
  height: 88px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  z-index: 100;
  bottom: 0;
  background: #fff;
  box-shadow: 10px -2px 8px #568bcf2e;
}

.uploadbody {
  .top {
    display: flex;
  }
  img {
    width: 300px;
    height: 240px;
  }
  .inputss {
    margin-top: 14px;
  }
}
</style>
